<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加社会服务</el-button>
    <el-table :data="services" style="margin-top: 10px" border>
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="serviceType" label="服务类型" />
      <el-table-column prop="score" label="得分" width="80" />
      <el-table-column prop="semester" label="学期" />
      <el-table-column prop="approved" label="是否审核" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.approved ? 'success' : 'warning'">
            {{ scope.row.approved ? '已通过' : '待审核' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="社会服务登记" @close="resetForm">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="服务类型" prop="serviceType">
          <el-input v-model="formData.serviceType" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" />
        </el-form-item>
        <el-form-item label="得分" prop="score">
          <el-input-number v-model="formData.score" :min="0" />
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-input v-model="formData.semester" placeholder="如 2024-2025 春季" />
        </el-form-item>
        <el-form-item label="是否审核" prop="approved">
          <el-switch v-model="formData.approved" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'SocialServicesModule',
  props: {
    studentId: { type: Number, required: true }
  },
  data() {
    return {
      services: [],
      dialogVisible: false,
      formData: this.initFormData(),
      rules: {
        serviceType: [{ required: true, message: '请输入服务类型', trigger: 'blur' }],
        description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        score: [{ required: true, type: 'number', min: 0, message: '请输入有效得分', trigger: 'change' }],
        semester: [{ required: true, message: '请输入学期', trigger: 'blur' }],
        approved: [{ required: true, type: 'boolean', message: '请选择是否审核', trigger: 'change' }]
      }
    }
  },
  watch: {
    studentId: {
      handler(newVal) {
        if (typeof newVal === 'number' && !isNaN(newVal)) {
          this.loadData()
        } else {
          this.services = []
        }
      },
      immediate: true
    }
  },
  methods: {
    initFormData() {
      return {
        id: null,
        studentId: this.studentId,
        serviceType: '',
        description: '',
        score: null,
        semester: '',
        approved: false
      }
    },
    async loadData() {
      try {
        const res = await axios.get(`/api/socialservices/student/${this.studentId}`)
        this.services = res.data || []
      } catch (e) {
        this.$message.error('加载社会服务失败')
        console.error('加载失败:', e)
      }
    },
    openAddDialog() {
      this.formData = this.initFormData()
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.formData = { ...row, studentId: this.studentId }
      this.dialogVisible = true
    },
    async submit() {
      try {
        this.formData.studentId = this.studentId
        const valid = await this.$refs.formRef.validate()
        if (!valid) return

        let res
        if (this.formData.id) {
          res = await axios.put('/api/socialservices', this.formData)
        } else {
          res = await axios.post('/api/socialservices', this.formData)
        }

        if (res.data.code === 200 || (typeof res.data === 'number' && res.data > 0)) {
          this.$message.success(this.formData.id ? '更新成功' : '添加成功')
          this.dialogVisible = false
          await this.loadData()
          this.$emit('save-success')
        } else {
          this.$message.error(res.data.message || (this.formData.id ? '更新失败' : '添加失败'))
        }
      } catch (e) {
        this.$message.error('提交失败')
        console.error('提交失败:', e)
      }
    },
    async handleDelete(id) {
      try {
        const res = await axios.delete(`/api/socialservices/${id}`)
        if (res.data.code === 200 || (typeof res.data === 'number' && res.data > 0)) {
          this.$message.success('删除成功')
          await this.loadData()
          this.$emit('save-success')
        } else {
          this.$message.error('删除失败')
        }
      } catch (e) {
        this.$message.error('删除失败')
        console.error('删除失败:', e)
      }
    },
    resetForm() {
      this.$refs.formRef?.resetFields()
      this.formData = this.initFormData()
    }
  }
}
</script>
